<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\News;
use fast\Tree;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Model extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';


    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Category');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where(['pid' => 0])
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->success();
    }

    public function copy($id = null)
    {
        set_time_limit(0);
        $row = $this->model->get($id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $categories = collection($this->model->where(['status' => "normal"])->select())->toArray();
        $tree = Tree::instance();
        $tree->init($categories, 'pid');
        $treeArr = $tree->getTreeArray($id);

        if (empty($treeArr)) {
            $this->error(__('该车型下没有分类'));
        }

        $newRootId = $this->model->insertGetId([
            'pid' => 0,
            'type' => 1,
            'name' => $row['name'],
            'nickname' => $row['nickname'],
            'coordinate' => $row['coordinate'],
            'image' => $row['image'],
            'createtime' => time(),
            'updatetime' => time(),
            'weigh' => 99,
            'status' => 'normal',
        ]);

        $this->copyCategories($treeArr, $newRootId);
        $this->success();
    }


    /**
     * 递归复制分类并保存到数据库的辅助函数
     * @param $categories 分类
     * @param $parentId 父ID
     * @return void
     */
    private function copyCategories($categories, $parentId)
    {
        foreach ($categories as $key => $category) {
            // 创建新分类记录并保存到数据库
            $newCategoryId = $this->model->insertGetId([
                'pid' => $parentId,
                'type' => 2,
                'name' => $category['name'],
                'nickname' => $category['nickname'],
                'coordinate' => $category['coordinate'],
                'image' => $category['image'],
                'createtime' => time(),
                'updatetime' => time(),
                'weigh' => 99,
                'status' => $category['status'],
            ]);

            // 递归调用复制子分类
            if (!empty($category['childlist'])) {
                $this->copyCategories($category['childlist'], $newCategoryId);
            }
            $this->copyNews($category['id'], $newCategoryId);
        }
    }


    /**
     * 拷贝文章
     * @param $oldCateId 旧CID
     * @param $newCateId 新CID
     * @return array|bool|\think\Collection|\think\model\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function copyNews($oldCateId, $newCateId)
    {
        $news = News::where(['cid' => $oldCateId])->select();
        if (!empty($news)) {
            $data = [];
            foreach ($news as $key => $new) {
                $data[$key] = [
                    'cid' => $newCateId,
                    'title' => $new['title'],
                    'content' => $new['content'],
                    'createtime' => time(),
                    'updatetime' => time(),
                    'weigh' => 99,
                    'is_recommend' => 0,
                    'status' => $new['status'],
                ];
            }
            return (new News())->saveAll($data);
        }
    }
}
